using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using SharedKernel.Infrastructure.EventBus;
using SharedKernel.Infrastructure.EventBus.RabbitMQ;
using Microsoft.Extensions.Options;

namespace SharedKernel.Infrastructure.EventBus
{
    /// <summary>
    /// 事件总线依赖注入扩展
    /// </summary>
    public static class EventBusDependencyInjection
    {
        /// <summary>
        /// 添加事件总线服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddEventBus(this IServiceCollection services)
        {
            // 注册事件总线实现
            services.AddSingleton<IEventBus, InMemoryEventBus>();
            // 如果你想使用RabbitMQ实现，可以取消下面的注释并注释上面的行
            // services.AddSingleton<IEventBus, RabbitMQEventBus>();
            // services.Configure<RabbitMQOptions>(options => { });

            return services;
        }

        /// <summary>
        /// 注册事件处理器
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="assembly">包含事件处理器的程序集</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddEventHandlers(this IServiceCollection services, Assembly assembly)
        {
            // 获取所有实现了IEventHandler接口的类型
            var handlerTypes = assembly.GetTypes()
                .Where(t => t.GetInterfaces()
                    .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEventHandler<>)))
                .ToList();

            // 注册所有事件处理器
            foreach (var handlerType in handlerTypes)
            {
                var interfaceType = handlerType.GetInterfaces()
                    .First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEventHandler<>));

                services.AddScoped(interfaceType, handlerType);
            }

            return services;
        }
    }
}